package notify

import (
	"errors"
	"time"

	"gitee.com/bjf-fhe/apicat/entry"
	"gitee.com/bjf-fhe/apicat/entry/handler"
	"gitee.com/bjf-fhe/apicat/platform"
	"github.com/sirupsen/logrus"
	"github.com/spf13/pflag"
)

type Handler interface {
	AddFlags(*pflag.FlagSet)
	Init(*handler.Config) error
}

var ErrNeedRetry = errors.New("need retry")

// type Notifier interface{}

// var currentHandler Handler
var currentIterNotifier platform.Notifier

type NotifyHandler struct {
	msgChan   chan *entry.LogEntry
	judgement *handler.Judgement
}

func (h *NotifyHandler) RecordEntry(en *entry.LogEntry) error {
	h.msgChan <- en
	return nil
}

func GetHandler(name string, currentHandler platform.Notifier, judgement *handler.Judgement) (handler.EntryHandler, error) {
	msgChan := make(chan *entry.LogEntry, 10)

	if fc, ok := currentHandler.(platform.Notifier); ok {
		currentIterNotifier = fc
	} else {
		currentIterNotifier = nil
	}
	if currentIterNotifier == nil {
		logrus.Fatal(name + "插件错误！")
	}
	var handler = &NotifyHandler{
		msgChan:   msgChan,
		judgement: judgement,
	}
	go handler.wait(msgChan)
	return handler, nil
}

func (h *NotifyHandler) wait(mc chan *entry.LogEntry) {
	var retry = 0
	var err error
	for msg := range mc {
		retry = 0
		for {
			if h.judgement.Judge(msg) {
				err = currentIterNotifier.NotifyAdd(msg)
			}
			if err != nil {
				if err == ErrNeedRetry {
					retry++
					time.Sleep(time.Duration(retry) * 50 * time.Millisecond)
					if retry < 10 {
						logrus.Info("Notify retry", retry)
						//只有retry<10的时候才继续
						continue
					}
					logrus.Errorln("Notify error override max retry", err)
				} else {
					logrus.Errorln("Notify error", err)
				}
			}
			//正常流程都直接break，终止内层，继续外层
			break
		}
	}
}
